/**
 * 
 */
package com.idea.zd.sys.service;
import java.util.ArrayList;
import java.util.List;

import com.idea.zd.sys.model.Admin;
import com.idea.zd.sys.model.Permission;
import com.idea.zd.sys.model.RolePer;
import com.idea.zd.sys.util.ZtreeNode;
import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.server.BaseService;
import org.apache.shiro.authz.annotation.RequiresPermissions;

/**
 * @author y.z
 */
public class PermissionService extends BaseService<Permission> {

	RolePerService rolePerService = new RolePerService();
	
	/**
	 * 查询权限分页
	 * @param curPage
	 * @return
	 */
	public Page<Permission> getPage(int curPage){
		List<Permission> permissionList = super.find("select * from sys_permission where parent_id is NULL order by sort,create_date desc");
		Page<Permission> page = new Page<Permission>(permissionList,1,10,1,0);
		return page;
	}
	
	/**
	 * 查询子权限分页
	 * @param curPage
	 * @param id
	 * @return
	 */
	public Page<Permission> getChildrePage(int curPage,int id){
		List<Permission> permissionList = super.find("select *from sys_permission where parent_id="+id+" order by sort,create_date desc");
		Page<Permission> page = new Page<Permission>(permissionList,1,10,1,0);
		return page;
	}
	

	
	/**
	 * 获取左菜单
	 * @param admin
	 * @return
	 */
	public List<Permission> getPermissionList(Admin admin){
		List<Permission> pList = new ArrayList<Permission>();
		
		String perStr = Db.queryStr("1SELECT GROUP_CONCAT(per_id) as perId FROM sys_role_per WHERE role_id = "+admin.get("type")+"");
		List<Permission> tempList = Permission.dao.find("SELECT s.parent_id,GROUP_CONCAT(id) as 'children_id' FROM sys_permission s WHERE s.id IN("+perStr+") and s.permission_type = 0 and s.parent_id is not null GROUP BY s.parent_id ORDER BY (select sort from sys_permission where id = s.parent_id),s.create_date DESC");
		
		for(Permission temp:tempList){
			Permission parentPer = super.findById(temp.get("parent_id"));
			
			List<Permission> childrenPerList = super.find("select * from sys_permission where id IN("+temp.get("children_id")+") order by sort,create_date desc");
			
			parentPer.put("childList",childrenPerList);
			pList.add(parentPer);
		}
		
		return pList;
	}


	/**
	 * 获取所有权限
	 * @param admin
	 * @return
	 */
	public List<Permission> getAllPermissionList(Admin admin){
		String perStr = Db.queryStr("SELECT GROUP_CONCAT(per_id) as perId FROM sys_role_per WHERE role_id = "+admin.get("type")+"");
		List<Permission> perList = super.find("SELECT s.* FROM sys_permission s  WHERE s.`id` IN ("+perStr+") AND s.`visit_url` IS NOT NULL");
		return perList;
	}
	
	/**
	 * 根据url获取
	 * @param url
	 * @return
	 */
	public String getNavigation(String url){
		String navigation = null;
		Permission permission  = super.findFirst("select * from sys_permission where visit_url = '"+url+"'");
		
		if(null != permission){
		        Permission per = super.findById(permission.get("parent_id"));
		        navigation = "<i class=\"Hui-iconfont\">"+per.getStr("icon")+"</i>"+per.getStr("permission_name") +"<span class=\"c-gray en\">&gt;</span>"+permission.getStr("permission_name");
		}
		
		return navigation;
	}
	
	/**
	 * 添加限权
	 * @param permission
	 * @return
	 */
	public boolean add(Permission permission){
		String sql = "select max(sort) as 'sort' from sys_permission where parent_id is NULL";
		
		if(!StrKit.isBlank(permission.getStr("parent_id"))){
			sql = "select max(sort) as 'sort' from sys_permission where parent_id = "+permission.get("parent_id")+"";
		}
		
		Permission sort = super.findFirst(sql);
		
		if(null != sort.get("sort")){
			permission.set("sort", Integer.parseInt(sort.get("sort").toString())+1);
		}else{
			permission.set("sort", 0);
		}
		
		return super.save(permission);
	}
	
	/**
	 * 根据id获取权限详情
	 * @param id
	 * @return
	 */
	public Permission getById(int id){
		return super.findById(id);
	}
	
	/**
	 * 更新限权
	 * @param permission
	 * @return
	 */
	public boolean update(Permission permission){
		return super.update(permission);
	}
	
	/**
	 * 删除限权
	 * @param id
	 * @return
	 */

	public boolean del(int id){
		boolean flag = false;
		
		if(null != super.findFirst("select * from sys_permission where parent_id = "+id+"")){
			
			if(super.update("delete from sys_permission where parent_id = "+id+"")){
				
				if(super.delById(id)){
					flag = true;
				}
			}
		}else{
			flag = super.delById(id);
		}
		
		return flag;
	}
	
	/**
	 * 验证url
	 * @param parentId
	 * @param id
	 * @param url
	 * @return
	 */
	public boolean validateUrl(int parentId,String id,String url){
		boolean flag = false;
		
		String sql = "select * from sys_permission where parent_id = "+parentId+" and visit_url = '"+url+"'";
		
		if(!StrKit.isBlank(id)){
			sql = "select * from sys_permission where parent_id = "+parentId+" and visit_url = '"+url+"' and id != "+id+"";
		}
		
		if(null == super.findFirst(sql)){
			flag = true;
		}
		
		return flag;
	}

	/**
	 * 获取树形权限列表
	 * @return
	 */
	public List<Permission> getTreePermission(int roleId){
		List<Permission> permissionList = super.find("select * from sys_permission where parent_id is null order by sort");
        int i = 0;
		for (Permission p:permissionList) {
			permissionList.set(i,getPermissionTreeById(p.getInt("id"),roleId));
			i++;

		}

		return permissionList;
	}
	
	@Before(Tx.class)
	public boolean setSort(int firstId,int secondId,int firstSort,int secondSort){
		Permission firstPer = new Permission();
		firstPer.set("id", firstId);
		firstPer.set("sort", firstSort);
		
		Permission secondPer = new Permission();
		secondPer.set("id", secondId);
		secondPer.set("sort", secondSort);
		
		if(firstPer.update() && secondPer.update()){
			return true;
		}
		
		return false;
	}

	/**
	 * 递归获取获取列表
	 * @param id
	 * @return
	 */
	private Permission getPermissionTreeById(int id,int roleId){
		Permission permission = super.findById(id);
		RolePer rolePer = rolePerService.findByRoleIdAndPerId(roleId,id);
		permission.put("open",true);
		permission.set("icon","");
		if(null == rolePer){
			permission.put("checked",false);
		}else{
			permission.put("checked",true);
		}
		List<Permission> children = new ArrayList<>();
		List<Permission> childrenList = super.find("select * from sys_permission where parent_id = "+id+" order by sort,create_date desc");

		for(Permission p:childrenList){
			Permission childPermission = getPermissionTreeById(p.getInt("id"),roleId);
			children.add(childPermission);
		}
		permission.put("children",children);
		return permission;
	}
}
